package com.agu.config.ds;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.lang.ArrayUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * MyBatis基础配置
 *
 */
@Configuration
@MapperScan(basePackages = {"com.agu.api.*.dao","com.agu.api.glt.*.dao","com.agu.mgt.*.dao"}, sqlSessionFactoryRef = "sqlSessionFactoryPrimary")
public class MyBatisPrimaryConfig {

	@Autowired
	@Qualifier("primaryDataSource")
	private DataSource primaryDataSource;

	@Primary
	@Bean("sqlSessionFactoryPrimary")
	public SqlSessionFactory sqlSessionFactoryPrimary() throws Exception {
		SqlSessionFactoryBean sqlsession = new SqlSessionFactoryBean();
		sqlsession.setDataSource(primaryDataSource); // 连接primary库
		
		// 扫描entity包 使用别名
		sqlsession.setTypeAliasesPackage("com.agu.entity");
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		// 使用jdbc的getGeneratedKeys获取数据库自增主键值
		configuration.setUseGeneratedKeys(true);
		// 使用列别名替换列名 select user as User
		configuration.setUseColumnLabel(true);
		// -自动使用驼峰命名属性映射字段 userId user_id
		configuration.setMapUnderscoreToCamelCase(true);
		sqlsession.setConfiguration(configuration);
		sqlsession.setFailFast(true);

		// 添加XML目录
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			
			Resource[] res1 = resolver.getResources("classpath*:mapper/api/**/*.xml");
			Resource[] res2 = resolver.getResources("classpath*:mapper/mgt/**/*.xml");

			Resource[] res =(Resource[]) ArrayUtils.addAll(res1, res2);

			sqlsession.setMapperLocations(res);
			return sqlsession.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	@Bean("sqlSessionTemplatePrimary")
	public SqlSessionTemplate sqlSessionTemplatePrimary(
			@Qualifier("sqlSessionFactoryPrimary") SqlSessionFactory springPrimarySqlSessionFactory) {
		return new SqlSessionTemplate(springPrimarySqlSessionFactory);
	}

}